package LeetCode.exercise;

import java.util.Random;

public class LC215 {
    public static void main(String[] args) {
        LC215 l = new LC215();
        int[] nums = {3,2,1,5,6,4};
        System.out.println(l.findKthLargest(nums, 2));
    }
    public int findKthLargest(int[] nums, int k) {
        return find(nums, 0, nums.length-1, k);
    }
    public int find(int[] nums, int l, int r, int k){
        int target = nums[new Random().nextInt(r-l+1) + l];
        int left = l-1, right = r+1, i = l;
        for(; i < right;){
            if(nums[i] < target){
                swap(nums, ++left, i++);
            } else if(nums[i] == target){
                i++;
            } else {
                swap(nums, --right, i);
            }
        }
        int a = left-l+1, b = i-1-left, c = r-right+1;
        if(k <= c){
            return find(nums, right, r, k);
        } else if(k <= c+b){
            return target;
        } else {
            return find(nums, l, left, k-c-b);
        }
    }
    public void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
